<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form onsubmit="return false;">
        <textarea name="message" style="width: 400px; height: 200px"></textarea>
        <input type="button" value="Send message" onclick="send(this.form.message.value)">
        <h3>服务端输出</h3>
        <textarea id="responseText" style="width: 400px; height: 200px"></textarea>
        <input type="button" value="Clear" onclick="javascript: document.getElementById('responseText').value = ''">
    </form>
    <script>
        var socket;
        var ta = document.getElementById('responseText');
        if (window.WebSocket) {
            socket = new WebSocket('ws://localhost:8080/ws');
            socket.onmessage = function (ev) {
                ta.value = ta.value + '\n' + ev.data;
            };

            socket.onopen = function (ev) {
                ta.value = 'Connection open';
            };

            socket.onclose = function (ev) {
                ta.value = 'Connection closed';
            };
        } else {
            alert("Browser doesn't support WebSocket");
        }

        function send(message) {
            if (!window.WebSocket || !message) {
                return;
            } 
            if (socket.readyState === WebSocket.OPEN) {
                socket.send(message);
            } else {
                alert('Connection not open');
            }
        }
    </script>
</body>
</html>